<?php
/**
 * Handler File Class
 *
 * @author admin <admin@wolive.cc>
 * @email admin@wolive.cc
 * @date 2017/06/01
 */
namespace app\admin\controller;

use think\Controller;
use app\admin\model\Admins;
use app\extra\push\Pusher;
use app\admin\iplocation\Ip;
use EasyWeChat\Foundation\Application;

header('Access-Control-Allow-Origin:*');
date_default_timezone_set("Asia/shanghai");

/**
 * 跨域公用控制器.
 */
class Event extends Controller
{
    /**
     * 离线，在线监控类.
     *
     * @returngetanswer void
     */
    public function index()
    {
        // pusher 访问的 地址
        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $webhook_signature = $_SERVER ['HTTP_X_PUSHER_SIGNATURE'];

        $body = file_get_contents('php://input');
        $expected_signature = hash_hmac('sha256', $body, $app_secret, false);

        if ($webhook_signature == $expected_signature) {

            $payload = json_decode($body, true);
            foreach ($payload['events'] as $event) {
                // 通知离线
                if ($event['name'] == 'channel_removed') {
                    // 客服 离线
                    if (strpos($event['channel'], 'kefu') === 0) {
                        $channel = str_replace('kefu', 'se', $event['channel']);
                        $id = str_replace('kefu', '', $event['channel']);
                        $pusher->trigger($channel, 'logout', array('message' => "客服已经下线"));
                        $res = Admins::table('wolive_service')->where('service_id', $id)->update(['state' => 'offline']);

                    } elseif (strpos($event['channel'], 'cu') === 0) {
                        // 访客 离线
                        $channel = str_replace('cu', '', $event['channel']);

                        $newstr = pack("H*", $channel);

                        $data = explode("/", $newstr);
                        $business_id = $data[1];

                        Admins::table("wolive_visiter")->where("channel", $channel)->update(["state" => 'offline']);

                        $res = Admins::table("wolive_queue")->where(['visiter_id' => $data[0], 'business_id' => $business_id])->find();
                        $id = $res['service_id'];

                        $arr = array(
                            'chas' => $channel
                        );
                        $pusher->trigger("kefu" . $id, 'logout', array('message' => $arr));

                        // 认领状态没有客服id，通知所有客服此人已经下线
                        if (!$id) {
                            $pusher->trigger('all'.$business_id, 'logout', array('message' => $arr));
                        }
                    }
                }

                // 通知在线
                if ($event["name"] == "channel_added") {

                    if (strpos($event['channel'], 'kefu') === 0) {
                        // 通知 访客，客服在线
                        $channel = str_replace('kefu', 'se', $event['channel']);
                        $id = str_replace('kefu', '', $event['channel']);
                        $res = Admins::table('wolive_service')->where('service_id', $id)->update(['state' => 'online']);
                        $pusher->trigger($channel, 'geton', array('message' => "客服上线"));

                    } elseif (strpos($event['channel'], 'cu') === 0) {
                        // 通知 客服 ，访客在线
                        $channel = str_replace('cu', '', $event['channel']);

                        $newstr = pack("H*", $channel);

                        $data = explode("/", $newstr);
                        $business_id = $data[1];

                        $res = Admins::table("wolive_queue")->where(['visiter_id' => $data[0], 'business_id' => $business_id])->find();

                        $res2 = Admins::table("wolive_visiter")->where("channel", $channel)->update(["state" => 'online']);

                        $id = $res['service_id'];
                        $arr = array(
                            'chas' => $channel
                        );
                        $pusher->trigger("kefu" . $id, 'geton', array('message' => $arr));

                        // 认领状态没有客服id，通知所有客服此人已经下线
                        if (!$id) {
                            $pusher->trigger('all'.$business_id, 'geton', array('message' => $arr));
                        }
                    }
                }
            }
            header("Status: 200 OK");
        } else {
            header("Status: 401 Not authenticated");
        }
    }

    /**
     *  后台添加客服接口
     *
     * @return string
     */
    public function registBusiness()
    {

        $post = $this->request->post();

        $time = time();

        if ($time - $post['timestamp'] > 60) {

            $data = ['code' => 1, 'msg' => '注册验证超时！'];
            return json_encode($data);
        }

        $token = md5($post['user_name'] . registToken . $post['timestamp']);

        if ($token == $post['token']) {

            if (!$post['nick_name']) {
                $post['nick_name'] = "管理员" . $post['user_name'];
            }

            $business_id = $post['user_name'];

            $arr = [
                'user_name' => $post['user_name'],
                'nick_name' => $post['nick_name'],
                'business_id' => $business_id,
                'password' => md5($post['user_name'] . "wolive" . $post['password']),
                'level' => 'manager',
            ];

            if (!empty($post['avatar'])) {
                $arr['avatar'] = $post['avatar'];
            }

            $business_info = Admins::table('wolive_business')->where('business_id', $business_id)->find();
            if ($business_info) {
                $data = ['code' => 2, 'msg' => '商户已经存在'];
                return json_encode($data);
            }

            $kefu_info = Admins::table('wolive_service')->where('user_name', $post['user_name'])->find();
            if ($kefu_info) {
                $data = ['code' => 3, 'msg' => "用户{$post['user_name']}已经存在"];
                return json_encode($data);
            }

            Admins::table('wolive_service')->insert($arr);
            Admins::table('wolive_business')->insert(['business_id' => $business_id, 'regist_timestamp' => time()]);

            $data = ['code' => 0, 'msg' => 'success'];

            return json_encode($data);

        } else {

            $data = ['code' => 1, 'msg' => '注册token验证失败！'];

            return json_encode($data);
        }
    }


    /**
     *  后台添加客服接口
     *
     * @return string
     */
    public function registKefu()
    {

        $post = $this->request->post();

        $time = time();

        if ($time - $post['timestamp'] > 60) {

            $data = ['code' => 1, 'msg' => '注册验证超时！'];
            return json_encode($data);
        }

        $token = md5($post['user_name'] . registToken . $post['timestamp']);

        if ($token == $post['token']) {

            if (!$post['nick_name']) {
                $post['nick_name'] = "管理员" . $post['user_name'];
            }

            if (!$post['business_id']) {
                $post['business_id'] = $post['user_name'];
            }

            $arr = [
                'user_name' => $post['user_name'],
                'nick_name' => $post['nick_name'],
                'business_id' => $post['business_id'],
                'password' => md5($post['user_name'] . "wolive" . $post['password']),
                'groupid'  => isset($post['groupid']) ? $post['groupid'] : 0,
            ];

            if (!empty($post['avatar'])) {
                $arr['avatar'] = $post['avatar'];
            }

            $business_info = Admins::table('wolive_business')->where('business_id', $post['business_id'])->find();
            if (!$business_info) {
                $data = ['code' => 2, 'msg' => '商户不存在'];
                return json_encode($data);
            }

            $kefu_info = Admins::table('wolive_service')->where('user_name', $post['user_name'])->find();
            if ($kefu_info) {
                $data = ['code' => 3, 'msg' => "用户{$post['user_name']}已经存在"];
                return json_encode($data);
            }

            $business_admin_info =  Admins::table('wolive_service')->where('user_name', $post['business_id'])->find();
            if (!$business_admin_info) {
                $data = ['code' => 4, 'msg' => "商家管理员{$post['business_id']}不存在"];
                return json_encode($data);
            }
            $arr['parent_id'] = $business_admin_info['service_id'];

            Admins::table('wolive_service')->insert($arr);

            $data = ['code' => 0, 'msg' => 'success'];

            return json_encode($data);

        } else {

            $data = ['code' => 1, 'msg' => '注册token验证失败！'];

            return json_encode($data);
        }
    }


    /**
     *  发言.
     *
     * @return string
     */
    public function chat()
    {
        $arr = $this->request->post();

        $content = Base::chatDecode($arr['content']);

        if (!ahost) {
            $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';

            $domain = $http_type . $_SERVER['HTTP_HOST'];
        } else {
            $domain = ahost;
        }

        $sarr = parse_url($domain);


        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = $domain;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $service_id = ($arr['service_id']);
        $visiter_id = ($arr['visiter_id']);
        $business_id = ($arr['business_id']);
        $avatar     = ($arr['avatar']);

        // 查询是否是黑名单
        if (Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'business_id' => $business_id,
            'state'       => 'in_black_list'
        ])->find()) {
            return ['code' => 1, 'msg' => '该会话已经关闭，禁止访问', 'id' => $service_id];
        }

        // 当前端点击确认不切换客服时会传递noswitch=service_id
        if ($service_id && empty($arr['noswitch']) || ($service_id && !empty($arr['noswitch']) && $arr['noswitch'] != $service_id)) {
            // 判断客服是否在线
            $service_data = Admins::table('wolive_service')->where(['business_id' => $business_id, 'service_id' => $service_id])->find();
            if (!$service_data) {
                return ['code' => 1, 'msg' => '该会话已经关闭，请刷新', 'id' => $service_id];
            } else {
                // 客服不在线
                if ($service_data['state'] !== 'online') {
                    // 查找对应组的其它在线客服
                    $group_id = (int)Admins::table('wolive_service')->where([
                        'business_id' => $business_id,
                        'service_id' => $service_id
                    ])->value('groupid');
                    $other_service = Admins::table('wolive_service')->where(['business_id' => $business_id, 'groupid' => $group_id, 'state' => 'online'])->find();
                    if ($other_service) {
                        return ['code' => 4, 'msg' => '该客服已经下线，是否转接其它客服？', 'id' => $service_id];
                    }
                }
            }
        }

        if ($service_id) {
            // 查询数据库是否有此会话，如果没有则是客户从关闭的会话发的消息，重新打开会话
            $queue_data = Admins::table("wolive_queue")->where([
                'visiter_id' => $visiter_id,
                'business_id' => $business_id,
                'service_id' => $service_id,
                'state' => 'normal'
            ])->find();
            if (!$queue_data) {
                // 查询是否有该访客的访客数据
                $visiter = Admins::table('wolive_visiter')->where(['visiter_id' => $visiter_id, 'business_id' => $business_id])->find();
                // 没有访客数据则提示刷新
                if (!$visiter) {
                    return ['code' => 1, 'msg' => '该会话已经关闭，请刷新', 'id' => $service_id];
                }
                $group_id = Admins::table('wolive_service')->where('service_id', $service_id)->value('groupid');
                $this->insertQueue($visiter_id, $service_id, $business_id, $group_id);
            }
        }

        $data = [
            'visiter_id'   => $visiter_id,
            'content'      => $content,
            'business_id' => $business_id,
            'avatar'      => $avatar,
            'service_id'  => $service_id,
            'record'      => $arr['record'],
            'timestamp'   => time(),
            'channel'     => bin2hex($visiter_id . '/' . $business_id)
        ];
        // 推送消息
        $pusher->trigger('kefu' . $service_id, 'cu-event', array('message' => $data));

        $data['direction'] = 'to_service';
        unset($data['record']);
        unset($data['avatar']);
        unset($data['channel']);

        Admins::table('wolive_chats')->insert($data);

        return ['code' => 0, 'msg' => 'success'];
    }


    /**
     * 分配客服
     *
     * @return mixed
     */
    public function notice()
    {

        $ip = $_SERVER["REMOTE_ADDR"];

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $arr = $this->request->post();

        if (!isset($arr['visiter_id'])  || !isset($arr['business_id'])) {

            $returndata = ['code' => 1, 'msg' => '数据不完整'];
            return $returndata;
        }

        $arr["visiter_name"] = ($arr['visiter_name']);
        $arr["business_id"] = ($arr['business_id']);
        $arr["from_url"] = ($arr['from_url']);
        $arr["avatar"] = ($arr['avatar']);
        $arr['visiter_id'] = ($arr['visiter_id']);
        $arr["channel"] = bin2hex($arr['visiter_id'] . '/' . $arr['business_id']);
        $arr['groupid'] = intval($arr['groupid']);
        $business = Admins::table('wolive_business')->where('business_id', $arr['business_id'])->find();

        $visiter_id = $arr['visiter_id'];
        $business_id = $arr['business_id'];
        $gid = $arr['groupid'];

        if ($business['state'] == 'close') {
            $returndata = ['code' => 1, 'msg' => '该商户客服已经禁止访问！'];
            return $returndata;
        }

        // 如果客服都没在线，跳转到留言板
        /*$serviceall = Admins::table('wolive_service')->where('business_id', $arr['business_id'])->where('groupid', $arr['groupid'])->where('state', 'online')->find();
        if (!$serviceall) {
            $returndata = ['code' => 3, 'msg' => '该商户该类客服都没在线'];
            return $returndata;
        }*/

        // 获取访客信息
        $visiter = Admins::table('wolive_visiter')->where(['visiter_id' => $visiter_id, 'business_id' => $business_id])->find();
        // 老访客
        if ($visiter) {
            // 替换成最新头像
            Admins::table('wolive_visiter')->where(['visiter_id' => $visiter_id, 'business_id' => $business_id])->update(['avatar' => $arr['avatar']]);
        // 新访客，插入一条记录
        } else {
            Admins::table('wolive_visiter')->insert([
                'visiter_id'   => $visiter_id,
                'visiter_name' => $arr["visiter_name"],
                'channel'      => $arr["channel"],
                'avatar'       => $arr['avatar'],
                'ip'           => $ip,
                'from_url'     => $arr['from_url'],
                'business_id'  => $business_id,
                'state'        => 'offline', // 这里一定是offline
            ]);
        }

        // 黑名单检查
        $inblacklist = Admins::table('wolive_queue')->where(['visiter_id' => $visiter_id, 'business_id' => $business_id, 'state' => 'in_black_list'])->limit(1)->find();
        if ($inblacklist) {
            return ['code' => 1, 'msg' => '禁止访问！'];
        }

        // 如果是专属连接
        if (!empty($arr['exclusive_service_name'])) {
            // 查找对应客服
            $exclusive_service = Admins::table("wolive_service")->field('service_id,avatar,business_id,groupid,nick_name,user_name,state')->where(['user_name' =>$arr['exclusive_service_name'], 'business_id' => $business_id])->find();
            // 如果客服存在则返回
            if ($exclusive_service) {
                $this->insertQueue($visiter_id, $exclusive_service['service_id'], $business_id, $gid);
                $exclusive_service['content'] = $this->getSentence($exclusive_service['service_id']);
                $returndata = ['code' => 0, 'msg' => 'success', 'data' => $exclusive_service];
                /*Admins::table('wolive_chats')->where([
                    'visiter_id' => $visiter_id,
                    'business_id' => $business_id,
                    'service_id' => 0
                ])->update(['service_id' => $exclusive_service['service_id']]);*/
                $this->acceptUnreadMessage($business_id, $exclusive_service['service_id'], $visiter_id, $arr['avatar'], !empty($arr['record'])?$arr['record']:'');
                return $returndata;
            }
            // 客服不存在
            $returndata = ['code' => 100, 'msg' => '客服不存在'];
            return $returndata;
        }

        // 要分配的客服信息
        $service_data = [];

        // 如果是老访客，并且老客服存在，并且老客服在线则返回上次老客服给他
        if ($visiter) {
            // 查找在线的老客服
            $old_online_services = Admins::table('wolive_queue')->query("select s.*, q.qid from wolive_service as s join wolive_queue as q on s.service_id = q.service_id where q.visiter_id = :visiter_id and s.business_id = :business_id and q.groupid = :groupid and s.state = 'online' order by qid desc limit 1", [
                'visiter_id'  => $visiter_id,
                'business_id' => $business_id,
                'groupid'     => $arr['groupid'],
            ]);
            // 有在线的老客服
            if ($old_online_services) {
                reset($old_online_services);
                $service_data = current($old_online_services);
                $service_id = $service_data['service_id'];
                $this->insertQueue($visiter_id, $service_data['service_id'], $business_id, $arr['groupid']);
                $service_data['content'] = $this->getSentence($service_id);
                unset($service_data['password']);
                $returndata = ['code' => 0, 'msg' => 'success', 'data' => $service_data];
                /*Admins::table('wolive_chats')->where([
                    'visiter_id' => $visiter_id,
                    'business_id' => $business_id,
                    'service_id' => 0
                ])->update(['service_id' => $service_data['service_id']]);*/
                $this->acceptUnreadMessage($business_id, $service_data['service_id'], $visiter_id, $arr['avatar'], !empty($arr['record'])?$arr['record']:'');
                return $returndata;
            }
        }

        // 认领模式
        if ($business['distribution_rule'] == 'claim') {
            // 将这个visiter_id的所有会话删除
            Admins::table('wolive_queue')->where([
                'visiter_id'  => $visiter_id,
                'business_id' => $business_id,
                'state'       => 'normal'
            ])->where('service_id', '<>', 0)->delete();

            // 队列里插入一个新的
            $this->insertQueue($visiter_id, 0, $business_id, $arr['groupid']);

            // 查询还有几个访客在等待
            $num = Admins::table('wolive_queue')->where(['service_id' => 0, 'business_id' => $business_id, 'groupid' => $arr['groupid']])->where('state', 'normal')->count();
            $class = Admins::table('wolive_group')->where('id', $arr['groupid'])->find();
            $allnotice = ['msg' => "公告:" . $arr['visiter_name'] . "需要" . $class['groupname'] . "的咨询", 'groupid' => $arr['groupid']];

            // 给所有该商家的客服推送信息
            $pusher->trigger("all" . $arr['business_id'], 'on_notice', array('message' => $allnotice));

            // 给当前访客返回等待人数
            $returndata = ['code' => 2, 'msg' => '等待认领！', 'data' => $num];
            return $returndata;

        // 智能分配模式
        } else {
             // 查找该分组所有在线客服
             $online_services = Admins::table('wolive_service')->field('service_id,avatar,business_id,groupid,nick_name,user_name,state')->where(['business_id' => $business_id, 'state' => 'online', 'groupid' => $gid])->select();

             // 客服都不在线，并且是老访客，并且老客服信息存在，则分配给老客服
             if (!$online_services && $visiter) {
                 // 找最近的一个老客服
                 $all_services = Admins::table('wolive_queue')->query("select s.*, q.qid from wolive_service as s join wolive_queue as q on s.service_id = q.service_id where q.visiter_id = :visiter_id and s.business_id = :business_id and q.groupid = :groupid order by qid desc limit 1", [
                     'visiter_id' => $visiter_id,
                     'business_id' => $business_id,
                     'groupid' => $arr['groupid']
                 ]);
                 if ($all_services) {
                     reset($all_services);
                     $service_data = current($all_services);
                     $this->insertQueue($visiter_id, $service_data['service_id'], $business_id, $gid);
                     $service_data['content'] = $this->getSentence($service_data['service_id']);
                     unset($service_data['password']);
                     $returndata = ['code' => 0, 'msg' => 'success', 'data' => $service_data];
                     /*Admins::table('wolive_chats')->where([
                         'visiter_id' => $visiter_id,
                         'business_id' => $business_id,
                         'service_id' => 0
                     ])->update(['service_id' => $service_data['service_id']]);*/
                     $this->acceptUnreadMessage($business_id, $service_data['service_id'], $visiter_id, $arr['avatar'], !empty($arr['record'])?$arr['record']:'');
                     return $returndata;
                 }
             }

             // 客服都不在线查找该分组下离线客服
             $services = $online_services ? $online_services : Admins::table('wolive_service')->field('service_id,avatar,business_id,groupid,nick_name,user_name,state')->where(['business_id' => $business_id, 'groupid' => $gid])->select();
            // 这个分组有客服
            if ($services) {
                // 选一个服务客户少的客服
                foreach ($services as $v) {
                    $num_info = Admins::table('wolive')->query("select count(q.visiter_id) as num from wolive_queue as q inner join wolive_visiter as v on q.visiter_id=v.visiter_id where q.service_id=".intval($v['service_id'])." and v.state='online' and q.state='normal'");
                    $num = isset($num_info[0]['num']) ? $num_info[0]['num'] : 0;

                    if (isset($service_data['num'])) {
                        if ($service_data['num'] > $num) {
                            $v['num'] = $num;
                            $service_data = $v;
                        }
                    } else {
                        $v['num'] = $num;
                        $service_data = $v;
                    }
                }

                $this->insertQueue($visiter_id, $service_data['service_id'], $business_id, $gid);

                // 将该访客的等待队列里的会话全部更新为这个客服认领
                /*Admins::table('wolive_chats')->where([
                    'visiter_id' => $visiter_id,
                    'business_id' => $business_id,
                    'service_id' => 0
                ])->update(['service_id' => $service_data['service_id']]);*/

                $this->acceptUnreadMessage($business_id, $service_data['service_id'], $visiter_id, $arr['avatar'], !empty($arr['record'])?$arr['record']:'');

                // 推送访客信息
                $pusher->trigger("ud" . $service_data['service_id'], 'on_notice', array('message' => $arr));

                $service_data['content'] = $this->getSentence($service_data['service_id']);
                unset($service_data['password']);
                $returndata = ['code' => 0, 'msg' => 'success', 'data' => $service_data];
                return $returndata;
            }

            $returndata = ['code' => 3, 'msg' => '该商户该类客服都没在线'];
            return $returndata;
        }
    }

    /**
     * 向队列里插入一条记录
     *
     * @param $visiter_id
     * @param $service_id
     * @param $business_id
     * @param $group_id
     */
    protected function insertQueue($visiter_id, $service_id, $business_id, $group_id) {
        $group_id = (int)$group_id;
        $rows = Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'service_id'  => $service_id,
            'business_id' => $business_id,
        ])->find();
        if ($rows['state'] == 'in_black_list') {
            return;
        }
        Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'service_id'  => $service_id,
            'business_id' => $business_id,
        ])->delete();
        Admins::table("wolive_queue")->insert([
            'visiter_id'  => $visiter_id,
            'service_id'  => $service_id,
            'business_id' => $business_id,
            'groupid'     => $group_id,
            'state'       => 'normal'
        ]);
    }

    /**
     * 客服接受访客的未读消息
     *
     * @param $visiter_id
     * @param $business_id
     * @param $service_id
     */
    protected function acceptUnreadMessage($business_id, $service_id, $visiter_id, $avatar, $record ='')
    {
        $message = Admins::table('wolive_chats')->where([
            'visiter_id' => $visiter_id,
            'business_id' => $business_id,
            'service_id' => 0
        ])->find();
        if ($message) {
            Admins::table('wolive_chats')->where([
                'visiter_id' => $visiter_id,
                'business_id' => $business_id,
                'service_id' => 0
            ])->update(['service_id' => $service_id]);

            $data = [
                'visiter_id'   => $visiter_id,
                'content'      => $message['content'],
                'business_id' => $business_id,
                'avatar'      => $avatar,
                'service_id'  => $service_id,
                'record'      => $record,
                'timestamp'   => time()
            ];
            // 推送消息
            $pusher = Base::getPusher();
            $pusher->trigger('kefu' . $service_id, 'cu-event', array('message' => $data));
        }

    }

    /**
     * 获得问候语
     *
     * @param $service_id
     * @return array|false|\PDOStatement|string|\think\Model
     */
    protected function getSentence($service_id) {
        $words = Admins::table('wolive_sentence')->where("service_id", $service_id)->where('state', 'using')->find();
        return $words ? $words['content'] : '您好！';
    }

    /**
     * 图片上传.
     *
     * @return [type] [description]
     */
    public function upload()
    {

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );


        $file = $this->request->file("upload");

        $post = $this->request->post();

        $service_id = ($post['service_id']);
        $visiter_id = ($post['visiter_id']);
        $business_id = ($post['business_id']);

        // 查询是否是黑名单
        if (Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'business_id' => $business_id,
            'service_id'  => $service_id,
            'state'       => 'in_black_list'
        ])->find()) {
            $returndata = ['code' => 1, 'msg' => '该会话已经关闭，禁止访问', 'id' => $service_id];
            return $returndata;
        }

        // 查询数据库是否有此会话，如果没有则是客户从关闭的会话发的消息，重新打开会话
        $queue_data = Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'business_id' => $business_id,
            'service_id'  => $service_id,
            'state'       => 'normal'
        ])->find();
        if (!$queue_data) {
            // 查询是否有该访客的访客数据
            $visiter = Admins::table('wolive_visiter')->where(['visiter_id' => $visiter_id, 'business_id' => $business_id])->find();
            // 没有访客数据则提示刷新
            if (!$visiter) {
                $returndata = ['code' => 1, 'msg' => '该会话已经关闭，请刷新', 'id' => $service_id];
                return $returndata;
            }
            $group_id = Admins::table('wolive_service')->where('service_id', $service_id)->value('groupid');
            $this->insertQueue($visiter_id, $service_id, $business_id, $group_id);
        }

        $post["timestamp"] = time();
        $post['service_id'] = $service_id;


        $name = $_FILES["upload"]["name"];

        $ext = substr($name, strripos($name, ".") + 1);
        if ($ext == 'html' || $ext == 'htm' || $ext == 'jsp' || $ext == 'php' || $ext == 'js') {

            $error = "不支持该文件格式！";
            $data = [
                "code" => -1,
                "msg" => $error,
                "data" => ""
            ];

            return $data;
        }

        if ($file) {
            $newpath = ROOT_PATH . "/public/upload/images/";
            $info = $file->move($newpath, time().rand());
            if ($info) {
                $file_data = file_get_contents($info->getRealPath());
                if (false !== strpos($file_data, '<?php')) {
                    unlink($info->getRealPath());
                    return ([
                        'code' => 400,
                        'msg'  => '文件非法',
                    ]);
                }

                $imgname = $info->getFilename();

                // 生成缩略图,减少图片尺寸
                $realpath = $info->getRealPath();
                $image = \think\Image::open($realpath);
                $image->thumb(1024, 1024)->save($realpath);

                $imgpath = "/upload/images/" . $imgname;

                $html = '<img onclick="getbig(this)" src="' . $imgpath . '" />';

                $post['content'] = $html;
                $post['channel'] = bin2hex($visiter_id . '/' . $business_id);


                $pusher->trigger('kefu' . $service_id, 'cu-event', array('message' => $post));

                $post['direction'] = 'to_service';
                unset($post['avatar']);
                unset($post['record']);
                unset($post['channel']);
                $res = Admins::table('wolive_chats')->insert($post);

                $data = [
                    "code" => 0,
                    "msg" => "",
                    "data" => $html
                ];

                return $data;
            }
        }
    }

    /**
     * 文件上传.
     *
     * @return [type] [description]
     */
    public function uploadfile()
    {

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $file = $this->request->file("folder");
        $post = $this->request->post();

        $service_id = ($post['service_id']);
        $visiter_id = ($post['visiter_id']);
        $business_id = ($post['business_id']);

        // 查询是否是黑名单
        if (Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'business_id' => $business_id,
            'service_id'  => $service_id,
            'state'       => 'in_black_list'
        ])->find()) {
            $returndata = ['code' => 1, 'msg' => '该会话已经关闭，禁止访问', 'id' => $service_id];
            return $returndata;
        }

        // 查询数据库是否有此会话，如果没有则是客户从关闭的会话发的消息，重新打开会话
        $queue_data = Admins::table("wolive_queue")->where([
            'visiter_id'  => $visiter_id,
            'business_id' => $business_id,
            'service_id'  => $service_id,
            'state'       => 'normal'
        ])->find();
        if (!$queue_data) {
            // 查询是否有该访客的访客数据
            $visiter = Admins::table('wolive_visiter')->where(['visiter_id' => $visiter_id, 'business_id' => $business_id])->find();
            // 没有访客数据则提示刷新
            if (!$visiter) {
                $returndata = ['code' => 1, 'msg' => '该会话已经关闭，请刷新', 'id' => $service_id];
                return $returndata;
            }
            $group_id = Admins::table('wolive_service')->where('service_id', $service_id)->value('groupid');
            $this->insertQueue($visiter_id, $service_id, $business_id, $group_id);
        }

        $post["timestamp"] = time();
        $post['service_id'] = $service_id;

        $name = $_FILES["folder"]["name"];

        $ext = substr($name, strripos($name, ".") + 1);

        if ($ext == 'html' || $ext == 'htm' || $ext == 'jsp' || $ext == 'php' || $ext == 'js') {

            $error = "不支持该文件格式！";
            $data = [
                "code" => -1,
                "msg" => $error,
                "data" => ""
            ];

            return $data;
        }

        if ($file) {
            $newpaths = ROOT_PATH . "/public/upload/files/";
            $info = $file->move($newpaths, time().rand());
            if ($info) {
                $file_data = file_get_contents($info->getRealPath());
                if (false !== strpos($file_data, '<?php')) {
                    unlink($info->getRealPath());
                    return ([
                        'code' => 400,
                        'msg'  => '文件非法',
                    ]);
                }
                $imgname = $info->getFilename();

                $imgpath = "/upload/files/" . $imgname;

                $html = "<div><a href='" . $imgpath . "' style='display: inline-block;text-align: center;min-width: 70px;text-decoration: none;' download='" . $name . "'><i class='layui-icon' style='font-size: 60px;'>&#xe61e;</i><br>" . $name . "</a></div>";


                $post['content'] = $html;
                $post['channel'] = bin2hex($visiter_id . '/' . $business_id);

                $pusher->trigger('kefu' . $service_id, 'cu-event', array('message' => $post));
                unset($post['avatar']);
                unset($post['record']);
                unset($post['channel']);
                $post['direction'] = 'to_service';
                $res = Admins::table('wolive_chats')->insert($post);

                $data = [
                    "code" => 0,
                    "msg" => "",
                    "data" => $imgpath
                ];

                return $data;
            }
        }
    }


    /**
     * 获取最近对话信息.
     *
     * @return string
     */
    public function chatdata()
    {

        $post = $this->request->post();
        $vid = $post['vid'];
        $service_id = $post['service_id'];

        if(!isset($post["hid"])) {
            $post["hid"] = '';
        }

        if ($post["hid"] == '') {

            $data = Admins::table('wolive_chats')->where(['service_id' => $service_id, 'visiter_id' => $vid, 'business_id' => $post['business_id']])->order('timestamp desc')->limit(10)->select();

            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $vid)->where('business_id', $post['business_id'])->find();
            $sdata = Admins::table('wolive_service')->where('service_id', $service_id)->where('business_id', $post['business_id'])->find();
            foreach ($data as $v) {

                if ($v['direction'] == 'to_service') {

                    $v['avatar'] = $vdata['avatar'];
                } else {

                    $v['avatar'] = $sdata['avatar'];
                }

            }
            reset($data);
        } else {

            $data = Admins::table('wolive_chats')->where(['service_id' => $service_id, 'visiter_id' => $vid, 'business_id' => $post['business_id']])->where('cid', '<', $post['hid'])->order('timestamp desc')->limit(10)->select();
            $vdata = Admins::table('wolive_visiter')->where('visiter_id', $vid)->where('business_id', $post['business_id'])->find();
            $sdata = Admins::table('wolive_service')->where('service_id', $service_id)->where('business_id', $post['business_id'])->find();

            foreach ($data as $v) {

                if ($v['direction'] == 'to_service') {
                    $v['avatar'] = $vdata['avatar'];
                } else {
                    $v['avatar'] = $sdata['avatar'];
                }
            }
            reset($data);
        }

        $result = array_reverse($data);

        // 如果有设置白名单，则不在白名单的商家聊天页面增加安全提示
        if(\think\Config::has('white_list') && !in_array($post['business_id'], \think\Config::get('white_list'))) {
            $last_cid = $result ? $result[count($result)-1]['cid'] : 0;
            $result[] = [
                'avatar'      => '/assets/images/index/warning.png',
                'business_id' => $post['business_id'],
                'cid'         => $last_cid,
                'content'     => "<div style=\"color:red;font-size:14px;\"><b>重要提示:<b>【&nbsp;此页面仅供测试，请勿相信任何信息，以免造成不必要的财产损失！】</div>",
                'direction'   => 'to_visiter',
                'service_id'  => $service_id,
                'state'       => 'unread',
                'timestamp'   => time(),
                'visiter_id'  => $vid
            ];
        }

        $data = ['code' => 0, 'data' => $result];
        return $data;
    }


    /**
     * 删除访客信息.
     *
     * @return boolAdmins
     */
    public function qdelete()
    {

        $post = $this->request->post();
        $result = Admins::table('wolive_queue')->where(['visiter_id' => $post['visiter_id'], 'business_id' => $post['business_id']])->delete();
        if ($result) {
            return true;
        } else {
            return false;
        }
    }


    /**
     *
     * @return string
     */
    public function apply()
    {
        $post = $this->request->post();

        $visiter = Admins::table('wolive_service')->where('service_id', $post['id'])->find();

        $queue = Admins::table('wolive_queue')->where(['visiter_id' => $post['visiter_id'], 'service_id' => $post['id']])->where('business_id', $post['business_id'])->update(['state' => 'normal']);


        $type = $visiter['state'];

        if ($type == 'offline') {

            $data = ['code' => 1, 'msg' => "对方不在线！"];

            return $data;
        }

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );
        $pusher->trigger("kefu" . $post['id'], "video", array("message" => "申请视频连接", "channel" => $post['channel'], "avatar" => $post['avatar'], 'username' => $post['name'], "cid" => $post['cha']));

        $data = ['code' => 0, 'msg' => 'success'];

        return $data;

    }

    /**
     *
     * [refuse description]
     * @return [type] [description]
     */
    public function refuse()
    {
        $post = $this->request->post();

        $sarr = parse_url(ahost);
        if ($sarr['scheme'] == 'https') {
            $state = true;
        } else {
            $state = false;
        }

        $app_key = app_key;
        $app_secret = app_secret;
        $app_id = app_id;
        $options = array(
            'encrypted' => $state
        );
        $host = ahost;
        $port = aport;

        $pusher = new Pusher(
            $app_key,
            $app_secret,
            $app_id,
            $options,
            $host,
            $port
        );

        $pusher->trigger("kefu" . $post['id'], "video-refuse", array("message" => "对方拒绝视频连接！"));
    }

    /**
     * [getquestion description]
     * @return [type] [description]
     */
    public function getquestion()
    {
        $post = $this->request->post();
        $business_id = $post['business_id'];
        $groupid = isset($post['groupid']) ? $post['groupid'] : 0;

        $result = Admins::table('wolive_question')->where('business_id', $business_id)->where('groupid', $groupid)->select();

        if ($result) {
            $arr = ['code' => 0, 'msg' => 'success', 'data' => $result];
            return $arr;
        }
    }

    /**
     *
     * [getanswer description]
     * @return [type] [description]
     */
    public function getanswer()
    {
        $post = $this->request->post();
        $qid = $post['qid'];
        $result = Admins::table('wolive_question')->where('qid', $qid)->find();
        if ($result) {
            $arr = ['code' => 0, 'msg' => 'success', 'data' => $result];
            return $arr;
        } else {
            $arr = ['code' => 1, 'msg' => '该问题已经被删除'];
            return $arr;
        }


    }

    /**
     *
     * [groupNum description]
     * @return [type] [description]
     */
    public function groupNum()
    {
        $num = Admins::table('wolive_group')->count();
        return $num;
    }

    /**
     *
     * [gettablist description]
     * @return [type] [description]
     */
    public function gettablist()
    {
        $post = $this->request->post();
        $business_id = $post['business_id'];
        $result = Admins::table('wolive_tablist')->where('business_id', $business_id)->select();

        $arr = ['code' => 0, 'msg' => 'success', 'data' => $result];

        return $arr;
    }


    /**
     *
     * [uploadimg description]
     * @return [type] [description]
     */
    public function uploadimg()
    {

        $file = $this->request->file("editormd-image-file");
        $name = $_FILES["editormd-image-file"]["name"];
        $arr = explode(".", $name);
        $ext = $arr[1];
        if ($ext == 'html' || $ext == 'htm' || $ext == 'jsp' || $ext == 'php' || $ext == 'js') {

            $error = "不支持该文件格式！";

            $data = [
                "code" => -1,
                "msg" => $error,
                "data" => ""
            ];
            $json = json_encode($data);

            return $json;
        }

        if ($file) {
            $newpaths = ROOT_PATH . "/public/upload/files/";
            $info = $file->move($newpaths, time().rand());
            if ($info) {

                $realpath = $info->getRealPath();
                $file_data = file_get_contents($realpath);
                if (false !== strpos($file_data, '<?php')) {
                    unlink($info->getRealPath());
                    return json_encode([
                        'code' => 400,
                        'msg'  => '文件非法',
                    ]);
                }

                $imgname = $info->getFilename();

                $imgpath = "/upload/files/" . $imgname;

                // 生成缩略图,减少图片尺寸
                $image = \think\Image::open($realpath);
                $image->thumb(1024, 1024)->save($realpath);

                $data = [
                    "success" => 1,
                    "msg" => "success",
                    "url" => $imgpath
                ];

                return json_encode($data);
            }
        }
    }


    /**
     *
     * [uploadVoice description]
     * @return [type] [description]
     */
    public function uploadVoice()
    {

        $http_type = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https')) ? 'https://' : 'http://';
        $file = $this->request->file('file');

        if ($file) {
            $newpath = ROOT_PATH . "/public/assets/upload/voices/";
            $info = $file->move($newpath, time().rand() . ".mp3");

            if ($info) {

                $file_data = file_get_contents($info->getRealPath());
                if (false !== strpos($file_data, '<?php')) {
                    unlink($info->getRealPath());
                    return json_encode([
                        'code' => 400,
                        'msg'  => '文件非法',
                    ]);
                }

                $imgname = $info->getFilename();
                $imgpath = $http_type . $_SERVER['HTTP_HOST'] . "/assets/upload/voices/" . $imgname;
                $arr = [
                    'data' => [
                        'src' => $imgpath
                    ]
                ];

                return json_encode($arr);
            } else {

                return false;
            }
        }
    }


    /**
     *
     * [getwaitnum description]
     * @return [type] [description]
     */

    public function getwaitnum()
    {

        $post = $this->request->post();

        if ($post['groupid'] == 0) {
            $count = Admins::table('wolive_queue')->where(['business_id' => $post['business_id'], 'state' => 'normal', 'service_id' => 0])->count();
        } else {
            $count = Admins::table('wolive_queue')->where(['business_id' => $post['business_id'], 'state' => 'normal', 'service_id' => 0, 'groupid' => $post['groupid']])->count();
        }
        return $count;
    }

}
